package com.example.library.vPage;


import com.example.library.ResourceTable;
import com.example.library.util.ImageLoadFactory;
import io.github.mthli.slice.shadowlayout.RippleShadowLayout;
import ohos.agp.components.*;
import ohos.app.Context;

import java.util.ArrayList;
import java.util.List;


public class CardPagerAdapter extends PageSliderProvider implements CardAdapter {

  private List<RippleShadowLayout> mViews;
  private List<Object> mData;
  private Context mContext;

  private int MaxElevationFactor = 9;

  @Override
  public int getMaxElevationFactor() {
    return MaxElevationFactor;
  }

  @Override
  public void setMaxElevationFactor(int MaxElevationFactor) {
    this.MaxElevationFactor = MaxElevationFactor;
  }

  public CardPagerAdapter(Context context) {
    mData = new ArrayList<>();
    mViews = new ArrayList<>();
    this.mContext = context;
  }

  public void addImgUrlList(List<Object> imgUrlList) {
    mData.addAll(imgUrlList);

    for (int i = 0; i < imgUrlList.size(); i++) {
      mViews.add(null);
    }
  }


  @Override
  public RippleShadowLayout getCardViewAt(int position) {
    return mViews.get(position);
  }

  @Override
  public int getCount() {
    return mData.size();
  }

  @Override
  public Object createPageInContainer(ComponentContainer container, int position) {
    Component view = LayoutScatter.getInstance(mContext).parse(ResourceTable.Layout_my_adapter, container, false);
    //Component view = LayoutScatter.from(container.getContext()).inflate(R.layout.adapter, container, false);
    view.setClickedListener(new Component.ClickedListener() {
      @Override
      public void onClick(Component component) {
        if (cardItemClickListener != null) {
          cardItemClickListener.onClick(position);
        }
      }
    });

    container.addComponent(view);
    bind(mData.get(position), view);
    RippleShadowLayout rippleShadowLayout = (RippleShadowLayout) view.findComponentById(ResourceTable.Id_ripple_shadow_layout);
    rippleShadowLayout.setElevation(MaxElevationFactor);
    mViews.set(position, rippleShadowLayout);
    return view;

  }

  @Override
  public void destroyPageFromContainer(ComponentContainer componentContainer, int position, Object o) {
    componentContainer.removeComponent((Component) o);
    mViews.set(position, null);
  }

  @Override
  public boolean isPageMatchToObject(Component component, Object o) {
    return component == o;
  }

  private void bind(Object imgUrl, Component view) {
    Image iv = (Image) view.findComponentById(ResourceTable.Id_item_iv);
    iv.setCornerRadius(30);
    ImageLoadFactory.getInstance().loadImage(iv, imgUrl, iv.getContext());

  }

  private OnCardItemClickListener cardItemClickListener;

  public interface OnCardItemClickListener {
    void onClick(int position);
  }

  public void setOnCardItemClickListener(OnCardItemClickListener cardItemClickListener) {
    this.cardItemClickListener = cardItemClickListener;
  }

}
